﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;

namespace Blob.Uploader
{
	public partial class Main : Form
	{
		BlobClient client;

		public Main()
		{
			InitializeComponent();
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog fbd = new FolderBrowserDialog();
			if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				txtLocalDirectory.Text = fbd.SelectedPath;
			}
		}

		private void chkCreateThumbnails_CheckedChanged(object sender, EventArgs e)
		{
			lblThumbnailPrefix.Visible = chkCreateThumbnails.Checked;
			txtThumbPrefix.Visible = chkCreateThumbnails.Checked;
		}

		private void btnTest_Click(object sender, EventArgs e)
		{
			client = new BlobClient(txtAccountName.Text, txtAccountKey.Text);
						
			if (client.TestConnection())
			{
				rtxtOutput.AppendText("Connection successful\n");
			}
			else
			{
				rtxtOutput.AppendText("Connection failed\n");
			}
			rtxtOutput.AppendText(client.Output.ToString());
		}

		private void btnUpload_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(txtLocalDirectory.Text))
			{
				MessageBox.Show("Need to select a local directory first");
				return;
			}

			if (client == null)
			{
				client = new BlobClient(txtAccountName.Text, txtAccountKey.Text);
			}
			client.Output.Clear();

			DirectoryInfo dir = new DirectoryInfo(txtLocalDirectory.Text);

			var currentBlobNames = client.GetExistingBlobNames(dir.Name);
			var files = dir.GetFiles();
			foreach (var file in files)
			{
				string contentType = GetContentType(Path.GetExtension(file.Extension));

				// create thumbnails?
				if (chkCreateThumbnails.Checked)
				{
					string thumbFileName = file.Name.Substring(0, file.Name.LastIndexOf(file.Extension)) + txtThumbPrefix.Text + file.Extension;
					
					// does a thumbnail exist?
					if (files.Count(fi => fi.Name == thumbFileName) == 0)
					{

						// create it locally
						Stream stream = CreateThumbnail(file.FullName);

						// save to blob
						bool thumbExists = currentBlobNames.Contains(thumbFileName);
						if (!thumbExists || (thumbExists & chkOverwrite.Checked))
						{
							client.SaveImage(dir.Name, thumbFileName, stream, null, contentType);
						}
					}
				}
				
				bool exists = currentBlobNames.Contains(file.Name);
				if (!exists || (exists & chkOverwrite.Checked))
				{
					client.SaveImage(dir.Name, file.Name, file.FullName, null, contentType);
				}
			}

			// include subfolders?

			
			rtxtOutput.AppendText(client.Output.ToString());
		}

		

		public static string GetContentType(string fileExt)
		{
			const string CONTENT_TYPE = "Content Type";
			const string DEFAULT_TYPE = "text/plain";
			string contentType = DEFAULT_TYPE;

			fileExt = fileExt.ToLower();

			// for some reason these are missing in win 7
			if (fileExt == ".jpg" || fileExt == ".jpeg")
			{
				return "image/jpeg";
			}

			RegistryKey rk = null;
			RegistryKey extKey = null;
			try
			{
				rk = Registry.ClassesRoot;
				extKey = rk.OpenSubKey(fileExt);

				if (extKey != null
					&& extKey.GetValue(CONTENT_TYPE) != null)
				{
					contentType = extKey.GetValue(CONTENT_TYPE).ToString();
				}
			}
			finally
			{
				if (extKey != null)
				{
					extKey.Close();
				}
				if (rk != null)
				{
					rk.Close();
				}
			}
			return contentType;
		}

		public Stream CreateThumbnail(string fileName)
		{
			Bitmap orig = new Bitmap(fileName);

			int width;
			int height;
			if (orig.Width > orig.Height)
			{
				width = 128;
				height = 128 * orig.Height / orig.Width;
			}
			else
			{
				height = 128;
				width = 128 * orig.Width / orig.Height;
			}

			Bitmap thumb = new Bitmap(width, height);
			using (Graphics graphic = Graphics.FromImage(thumb))
			{
				graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
				graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
				graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

				graphic.DrawImage(orig, 0, 0, width, height);
				MemoryStream ms = new MemoryStream();
				thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

				ms.Seek(0, SeekOrigin.Begin);
				return ms;
			}
		}
	}
}
